package com.xiangyu.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * java类简单作用描述
 *
 * @ProjectName: springboot-demo
 * @Package: com.xiangyu.demo.utils
 * @Description: java类作用描述
 * @Author: 向羽
 * @CreateDate: 2018/1/22 14:38
 * @UpdateUser: 向羽
 * @UpdateDate: 2018/1/22 14:38
 * @UpdateRemark: The modified content
 * @Version: 2.0
 */
@Component
public class RedisUtil {

    private Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    @Autowired
    private RedisTemplate redisTemplate;

    /**
      * @Author: 向羽
      * @Description: 判断缓存中是否有对应的value
      * @Date: 2018/1/22 14:39
      */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
      * @Author: 向羽
      * @Description: 写入缓存
      * @Date: 2018/1/22 14:39
      */
    public boolean set(final String key, Object value) {

        return (Boolean) redisTemplate.execute((RedisCallback)(connection)->{
            connection.set(redisTemplate.getStringSerializer().serialize(key),redisTemplate.getStringSerializer().serialize(value));
            logger.debug("save key:{},value:{}",key,value);
            return true;
        });
    }

    /**
      * @Author: 向羽
      * @Description: 写入缓存
      * @Date: 2018/1/22 14:46
      */
    public boolean set2(final String key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



}
